/* 
 * Copyright (c) 2021, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.boot.component.uploader;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import com.cory.boot.base.BaseController;
import com.cory.boot.domain.bean.Result;
import com.cory.utils.file.FileUtils;
import com.cory.utils.lang.DateUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author xiongcong
 * @date 2021-05-22
 */
@Slf4j
@RestController
@RequestMapping("/uploader")
public class UploaderController extends BaseController {
    
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/file", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> uploadFile(MultipartFile file, HttpServletRequest request) throws Exception {
        if (file == null) {
            if (request instanceof MultipartHttpServletRequest) {
                MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
                Iterator iter = mr.getFileMap().values().iterator();
                if (iter.hasNext()) {
                    file = (MultipartFile) iter.next();
                }
            }
        }

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String newName = DateUtils.getDate("yyyyMMddHHmmss") + "_" + new Random().nextInt(1000) + "." + suffix;
        
        String fileId = "/resource/" + DateUtils.getYear() + "/" + DateUtils.getMonth() + "/" + newName;
        String fullPath = UploaderConfig.resource + fileId;

        FileUtils.createFile(fullPath);
        FileUtils.copyToFile(file.getInputStream(), new File(fullPath));
        
        Map<String, String> data = new HashMap<String, String>();
        data.put("fileId", fileId);
        data.put("fileUrl", UploaderUtils.getUrl(fileId));
        data.put("fileName", fileName);
        data.put("suffix", suffix);
        
        log.info(JSONObject.toJSONString(data));
        return Result.success().data(data);
    }

}
